package com.example.j2025_11_10.controller;

import com.example.j2025_11_10.Model.*;
import com.example.j2025_11_10.constant.Constants;
import com.example.j2025_11_10.service.*;
//import com.example.j2025_11_10.service.BookService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    public AddBookService addBookService;

    @Autowired
    public GetListByPageService getListByPageService;

    @Autowired
    public QueryBookByIdService queryBookByIdService;

    @Autowired
    public UpdateBookService updateBookService;
    @Autowired
    public BatchDeleteBookService batchDeleteBookService;
    //测试接口
//    @RequestMapping("/t1")
//    public Result t1(String test1){
//        return Result.success(10);
//    }
    //添加图书
    @RequestMapping("/addBook")
    public Result addBook(BookInfo bookInfo){
        String str = addBookService.addBook(bookInfo);
        if ("".equals(str)) return Result.success(str);
        else return Result.fail(str);

    }

    //分页列表
    @RequestMapping("/getListByPage")
    public Result<PageResult<BookInfo>> getListByPage(PageInfo pageInfo, HttpSession session){
        //参数校验
        //返回数据
        if (session.getAttribute(Constants.SESSION_USER_KEY)==null){
            return Result.unlogin();
        }
        UserInfo userInfo = (UserInfo)session.getAttribute(Constants.SESSION_USER_KEY);
        if (userInfo==null || userInfo.getId()<=0){
            //用户未登录
            return Result.unlogin();
        }
        //已登入
        PageResult<BookInfo> booklist = getListByPageService.getListByPage(pageInfo);
        return Result.success(booklist);
    }
    //根据id查图书
    @RequestMapping("/queryBookById")
    public Result queryBookById(Integer bookId){
        return Result.success(queryBookByIdService.queryBookById(bookId));
    }
    //更新图书
    @RequestMapping("/updateBook")
    public Result updateBook(BookInfo bookInfo){
        log.info("修改图书:{}" ,bookInfo);
        try {
            updateBookService.updateBook(bookInfo);
            return Result.success("");
        }catch (Exception e){
            log.error("修改图书失败:{}",e);
            return Result.fail(e.getMessage());
        }
    }
    @RequestMapping("/batchDeleteBook")
    //批量删除
    public Result batchDeleteBook(@RequestParam List<Integer> ids){
        String str = batchDeleteBookService.batchDeleteBook(ids);
        if("".equals(str)) return Result.success(str);
        else return Result.fail(str);

    }

}
